<template>
  <div>
    <a-col :span="24">
      <p class="text-lg font-bold">出货单</p>
      <vxe-form
        title-colon
        ref="formRef"
        title-align="right"
        title-width="100"
        @submit="submitEvent"
        @reset="resetEvent($event)"
        :data="formData"
        :rules="formRules"
      >
        <vxe-form-gather span="24">
          <vxe-form-item title="办理人" field="user_id" span="4">
            <template #default="{ data }">
              <vxe-select v-model="data.user_id" placeholder="请选择办理人">
                <vxe-option
                  v-for="(g, index) in searchTableOpt.userOpt"
                  :label="g.label"
                  :value="g.id"
                  :key="index"
                >
                </vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item title="单位" field="site_id" span="4">
            <template #default="{ data }">
              <vxe-select
                v-model="data.site_id"
                placeholder="请选择单位"
                @change="changeSite"
              >
                <vxe-option
                  v-for="(g, index) in searchTableOpt.siteOpt"
                  :label="g.label"
                  :value="g.id"
                  :key="index"
                >
                </vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item title="部门" field="department_id" span="4">
            <template #default="{ data }">
              <vxe-select
                v-model="data.department_id"
                placeholder="请选择部门"
                @change="changeDepartment"
              >
                <vxe-option
                  v-for="(g, index) in searchTableOpt.departmentOpt"
                  :label="g.label"
                  :value="g.id"
                  :key="index"
                >
                </vxe-option>
              </vxe-select>
            </template>
          </vxe-form-item>
          <vxe-form-item title="日期" field="sale_date" span="4">
            <template #default="{ data }">
              <vxe-input
                v-model="data.sale_date"
                placeholder="请选择出货日期"
                type="datetime"
                transfer
                formatter="formatDate"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="单据编号" field="sale_order_no" span="4">
            <template #default="{ data }">
              <vxe-input
                v-model="data.sale_order_no"
                placeholder="请输入单据编号"
              ></vxe-input>
            </template>
          </vxe-form-item>
          <vxe-form-item title="商品" field="receipt_items" span="24">
            <template #default="{ data }">
              <vxe-toolbar ref="toolbarRef" print export>
                <template #buttons>
                  <vxe-button status="primary" @click="addReceiptItem(-1)"
                    >空白新增</vxe-button
                  >

                  <vxe-button @click="removeSelectReceiptItem"
                    >删除选中</vxe-button
                  >
                  <vxe-button status="primary" @click="pickTemplate"
                    >模板导入</vxe-button
                  >
                </template>
              </vxe-toolbar>
              <!--              table-->
              <vxe-table
                border
                show-overflow
                show-footer
                keep-source
                :print-config="{
                  sheetName: `${formData.sale_order_no}`,
                }"
                :export-config="{
                  filename: `${formData.sale_order_no}`,
                }"
                :resize-config="{}"
                :is-hover="true"
                :edit-rules="validRules"
                ref="xTable"
                :column-config="{ resizable: true }"
                min-height="200"
                :data="formData.saleorder_items"
                :footer-method="footerMethod"
                :edit-config="{
                  trigger: 'click',
                  mode: 'row',
                  showStatus: true,
                }"
              >
                <vxe-column type="checkbox" width="60"> </vxe-column>
                <vxe-column
                  field="supplier_name"
                  title="供应商"
                  sortable
                  :edit-render="{
                    autofocus: '.vxe-input--inner',
                    defaultValue: '默认的名字',
                  }"
                >
                  <template #edit="{ row }">
                    <vxe-select
                      v-model="row.supplier_name"
                      placeholder="请选择供应商"
                      filterable
                      @change="supplierChange(row, $event)"
                    >
                      <vxe-option
                        v-for="(g, index) in searchTableOpt.supplierOpt"
                        :label="`${g.label},id:${g.id}`"
                        :value="g.label"
                        :key="index"
                      >
                      </vxe-option>
                    </vxe-select>
                  </template>
                </vxe-column>

                <vxe-column
                  field="supplier_id"
                  title="供应商id"
                  sortable
                  :edit-render="{
                    autofocus: '.vxe-input--inner',
                    defaultValue: '默认的名字',
                  }"
                >
                  <template #edit="{ row }">
                    <vxe-input
                      disabled
                      v-model="row.supplier_id"
                      type="text"
                    ></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column
                  field="product_name"
                  title="商品名称"
                  sortable
                  :edit-render="{
                    autofocus: '.vxe-input--inner',
                    defaultValue: '默认的名字',
                  }"
                >
                  <template #edit="{ row }">
                    <!--                    使用懒加载，带搜索功能-->
                    <vxe-select
                      v-model="row.product_name"
                      placeholder="请选择商品"
                      filterable
                      @change="productChangeName(row, $event)"
                    >
                      <vxe-option
                        v-for="(g, index) in searchTableOpt.productOpt"
                        :label="g.name"
                        :value="g.name"
                        :key="index"
                      >
                      </vxe-option>
                    </vxe-select>
                  </template>
                </vxe-column>

                <vxe-column
                  field="product_id"
                  title="商品id"
                  sortable
                  :edit-render="{
                    autofocus: '.vxe-input--inner',
                    defaultValue: '默认的名字',
                  }"
                >
                  <template #edit="{ row }">
                    <vxe-input disabled placeholder="请输入id"></vxe-input>
                  </template>
                </vxe-column>

                <vxe-column
                  field="unit"
                  title="单位"
                  sortable
                  :edit-render="{
                    autofocus: '.vxe-input--inner',
                    defaultValue: '默认的名字',
                  }"
                >
                  <template #edit="{ row }">
                    <vxe-input disabled v-model="row.unit"></vxe-input>
                  </template>
                </vxe-column>

                <vxe-column
                  field="net_qty"
                  title="库存"
                  sortable
                  :edit-render="{
                    autofocus: '.vxe-input--inner',
                    defaultValue: '',
                  }"
                >
                  <template #edit="{ row }">
                    <vxe-input disabled v-model="row.net_qty"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column
                  field="qty"
                  title="数量"
                  sortable
                  :edit-render="{
                    autofocus: '.vxe-input--inner',
                    defaultValue: '',
                  }"
                >
                  <template #edit="{ row }">
                    <!--                    使用懒加载，带搜索功能-->
                    <vxe-input
                      v-model="row.qty"
                      type="number"
                      @change="qtyChange(row, $event)"
                    ></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column
                  field="unit_price"
                  title="单价"
                  sortable
                  :edit-render="{
                    autofocus: '.vxe-input--inner',
                    defaultValue: '默认的名字',
                  }"
                >
                  <template #edit="{ row }">
                    <vxe-input disabled v-model="row.unit_price"></vxe-input>
                  </template>
                </vxe-column>

                <vxe-column
                  field="memo"
                  title="备注"
                  sortable
                  :edit-render="{
                    autofocus: '.vxe-input--inner',
                    defaultValue: '默认的名字',
                  }"
                >
                  <template #edit="{ row }">
                    <!--                    使用懒加载，带搜索功能-->
                    <vxe-input v-model="row.memo"></vxe-input>
                  </template>
                </vxe-column>
                <vxe-column title="金额（元）" field="amount" sortable>
                  <template #default="{ row }">
                    <span>{{ countAmount(row) }}</span>
                  </template>
                </vxe-column>
              </vxe-table>
              <!--              table-->
            </template>
          </vxe-form-item>

          <vxe-form-gather span="16">
            <vxe-form-item title="总金额" field="amount" span="4">
              <template #default="{ data }">
                <vxe-input
                  v-model="formData.amount"
                  placeholder="请输入金额"
                ></vxe-input>
              </template>
            </vxe-form-item>
          </vxe-form-gather>
        </vxe-form-gather>

        <vxe-form-item align="left" span="24">
          <template #default>
            <vxe-button
              type="submit"
              icon="vxe-icon-save"
              status="primary"
              content="提交"
            ></vxe-button>
            <vxe-button
              type="reset"
              icon="vxe-icon-undo"
              content="重置"
            ></vxe-button>
          </template>
        </vxe-form-item>
      </vxe-form>
    </a-col>

    <DraggableModal
      v-model:open="showEditPopup"
      :width="'1400px'"
      title="模板选择"
      :keyboard="false"
      :footer="false"
    >
      <vxe-table
        border
        show-overflow
        keep-source
        :is-hover="true"
        :column-config="{ resizable: true }"
        min-height="200"
        :data="purchaseTemplates"
      >
        <vxe-column field="id" title="模板id" sortable> </vxe-column>
        <vxe-column field="name" title="模板名称" sortable> </vxe-column>

        <vxe-column field="action" title="操作" sortable>
          <template #default="{ row }">
            <a-button type="primary" @click="importAction">导入</a-button>
            <a-button type="link" @click="showTemplate(row)">查看</a-button>
          </template>
        </vxe-column>
      </vxe-table>
      <a-collapse v-model:activeKey="collapseKey">
        <a-collapse-panel header="模板数据" key="1">
          <vxe-table
            border
            show-overflow
            keep-source
            :is-hover="true"
            :column-config="{ resizable: true }"
            min-height="200"
            :data="productData"
          >
            <vxe-column field="id" title="货品id" sortable> </vxe-column>
            <vxe-column field="name" title="名称" sortable> </vxe-column>
            <vxe-column field="unit" title="单位" sortable> </vxe-column>
            <vxe-column field="spec" title="规格" sortable> </vxe-column>
            <vxe-column field="price" title="价格" sortable> </vxe-column>
          </vxe-table>
        </a-collapse-panel>
      </a-collapse>
    </DraggableModal>
  </div>
</template>

<script setup lang="ts">
import useRuleStore from "@/store/modules/rule";
import Api from "@/api/backend/api";
import XEUtils from "xe-utils";
import { message } from "ant-design-vue";
import { VXETable } from "vxe-table";
const activeKey = ref("1");
const { gridOptions } = useSaleOrder();
const xGrid = ref();
const toolbarRef = ref();

const ruleStore = useRuleStore();
const router = useRouter();

const userOpt = ref([]);

const xTable = ref();

const formRef = ref();
// region 表格数据
const receipt_items = ref([
  {
    id: null,
    supplier_id: null,
    supplier_name: "",
    sale_order_id: null,
    bill_no: null,
    product_id: null,
    product_name: "",
    quantity: 0,
    serial_no: null,
    unit_price: null,
    amount: 0,
    discount_amount: 1,
    memo: null,
  },
]);

// 定义一个非响应式数据add_receipt_items
let add_receipt_items = {
  id: null,
  site_id: null,
  department_id: null,
  supplier_id: null,
  supplier_name: null,
  sale_order_id: null,
  receipt_type: 3, //发货
  product_id: null,
  product_name: "",
  quantity: 0,
  serial_no: null,
  qty: 0,
  net_qty: 0,
  unit_price: 0,
  amount: 0,
  discount_amount: 1,
  memo: null,
};

let formData = reactive({
  sale_date: XEUtils.toDateString(new Date(), "yyyy-MM-dd HH:mm:ss"),
  site_id: null,
  department_id: null,
  sale_order_no: "CHDD-" + XEUtils.toDateString(new Date(), `yyyyMMddHHmmss`),
  status: 1,
  user_id: null,
  quantity: 0,
  amount: 0,
  order_type: 3,
  saleorder_items: [],
});

const removeSelectReceiptItem = (row) => {
  const $table = xTable.value;
  if ($table) {
    $table.removeCheckboxRow();
  }
};
const searchTableOpt = ref({
  supplierOpt: [],
  productOpt: [],
  userOpt: [],
  siteOpt: [],
  departmentOpt: [],
});

onMounted(async () => {
  const productOpt = await Api.productController.option({
    filters: {
      supplier_id: searchTableForm.value.supplier_id,
      seeNull: "seeNull",
    },
  });
  const useropt = await Api.userController.option();
  const supplieropt = await Api.supplierController.option({
    filters: {
      id: null,
    },
  });
  const siteOpt = await Api.siteController.option();
  searchTableOpt.value.siteOpt = siteOpt;
  searchTableOpt.value.productOpt = productOpt;
  searchTableOpt.value.userOpt = useropt;
  searchTableOpt.value.supplierOpt = supplieropt;
  const $table = xTable.value;
  const $toolbar = toolbarRef.value;
  if ($table && $toolbar) {
    $table.connect($toolbar);
  }
});
//当站点变化时
const changeSite = async (event) => {
  const departmentOpt = await Api.departmentController.option({
    sid: event.value,
    seeNull: "seeNull",
  });
  searchTableOpt.value.departmentOpt = departmentOpt;
  //add_receipt_items中的site_id更新
  add_receipt_items.site_id = event.value;
};
const changeDepartment = (event) => {
  add_receipt_items.department_id = event.value;
};
const searchTableForm = ref({
  supplier_id: null,
  product_id: null,
});

// 这三个方法会相互联动
const supplierChange = async (row, event) => {
  row["supplier_id"] = searchTableOpt.value.supplierOpt.filter(
    (item) => item.label == row.supplier_name
  )[0]["id"];
  searchTableOpt.value.productOpt = await Api.productController.option({
    filters: {
      supplier_id: row["supplier_id"],
      seeNull: "seeNull",
    },
  });
  row["product_name"] = "";
  //同时
  row["unit_price"] = 0;
  row["unit"] = 0;
  row["product_id"] = 0;
};

const productChangeName = async (row, event) => {
  const product = searchTableOpt.value.productOpt.filter(
    (item) => item.name == row.product_name
  )[0];
  row["product_name"] = product["name"];
  //同时
  row["unit_price"] = product["price"];
  row["unit"] = product["unit"];
  row["product_id"] = product["id"];
  row["serial_no"] = product["code"];
  row["net_qty"] = product["net_qty"];
};

// 输入商品数量时
const qtyChange = (row, event) => {
  row.amount = row.qty * row.unit_price;
};

//直接新增
const addReceiptItem = async (row) => {
  const $table = xTable.value;
  if ($table) {
    const record = add_receipt_items;
    const { row: newRow } = await $table.insertAt(record, row);
    await $table.setEditCell(newRow, "supplier_id");
  }
};

// 复制新增
const copyReceiptItem = async (row) => {
  const $table = xTable.value;
  if ($table) {
    receipt_items.value[0]["_X_ROW_KEY"] = null;
    const record = receipt_items.value[0];
    const { row: newRow } = await $table.insertAt(record, row);
    await $table.setEditCell(newRow, "goods_id");
  }
};

const sumNum = (list: ReceiptItemModel[], field: string) => {
  let count = 0;
  list.forEach((item) => {
    count += item[field];
  });
  return count;
};

const countAmount = (row: ReceiptItemModel) => {
  row.qty = +row.qty;
  let mount = row.unit_price * row.qty;

  return mount;
};

const countAllAmount = (data: ReceiptItemModel[]) => {
  let count = 0;
  data.forEach((row) => {
    count = count + countAmount(row);
  });
  return count;
};


// 表格校验
const validRules = ref<VxeTablePropTypes.EditRules>({
  supplier_name: [{ required: true, message: "供应商必须填写" }],
  product_name: [{ required: true, message: "商品名称必须填写" }],
  unit: [{ required: true, message: "单位必须填写" }],
  qty: [
    { required: true, message: "数量必须填写" },
    {
      validator({ row, cellValue }) {
        if (row.net_qty < Number(cellValue)) {
          return new Error("库存不足请重新填写");
        }
      },
    },
  ],
});

const footerMethod: VxeTablePropTypes.FooterMethod<ReceiptItemModel> = ({
  columns,
  data,
}) => {
  return [
    columns.map((column, columnIndex) => {
      if (columnIndex === 0) {
        return "合计";
      }
      if (columnIndex === 1) {
        //表单提交时会自动触发该事件。这个时候需要更新formData中的amount
        let count = countAllAmount(data);
        formData.amount = count;
        return `共 ${count} 元`;
      }
      if (columnIndex === 6) {
        formData.quantity = sumNum(data, "qty");
        return `数量： 共 ${sumNum(data, "qty")}`;
      }
      return "-";
    }),
  ];
};
// endregion
const formRules = ref<VxeFormPropTypes.Rules>({
  supplier_name: [{ required: true, content: "请选择供货单位" }],
  site_id: [
    {
      required: true,
      content: "选择单位",
    },
  ],
  department_id: [
    {
      required: true,
      content: "选择部门",
    },
  ],
  user_id: [
    {
      required: true,
      content: "请选择经手人",
    },
  ],
  record_date: [{ required: true, content: "请选择制单日期" }],
});

// 提交表单
const submitEvent = async () => {
  const $table = xTable.value;
  //验证表格中的数据，如果失败则返回
  let error = await $table.validate();
  if (error) {
    message.error("数据错误，请检查");
    return;
  }
  const { tableData } = $table.getTableData();
  if (tableData.length == 0) {
    message.error("请添加商品，请检查");
    return;
  }
  formData.saleorder_items = tableData;

  // 等于子项目数量之和
  formData.quantity = +formData.quantity;
  formData.amount = +formData.amount;
  formData.saleorder_items.forEach((item) => {
    item.qty = +item.qty;
    item.product_id = +item.product_id;
    item.unit_price = +item.unit_price;
    item.amount = +item.amount;
  });

  await Api.saleOrderController.store(formData);
  // 清空表单，
  $table.clearData();
  // 清空表格
};
const resetEvent = (e) => {
  formData.saleorder_items = [];
  message.success("重置成功");
};

//模板导入
const showEditPopup = ref(false);
const collapseKey = ref("1");
const purchaseTemplates = ref([]);
const productData = ref([]);
const pickTemplate = async () => {
  showEditPopup.value = true;
  purchaseTemplates.value = await Api.saletemplateController.index();
};
const showTemplate = async (row) => {
  productData.value = await Api.saletemplateController.product({
    id: row.id,
  });
  collapseKey.value = "1";
};

const importAction = async () => {
  if (productData.value.length == 0) {
    return message.error("请先查询数据后导入");
  }
  let insertData = productData.value.map((item) => {
    return {
      supplier_id: item.supplier_id,
      supplier_name: item.supplier.name,
      receipt_type: 1,
      product_id: item.id,
      product_name: item.name,
      unit_price: item.price,
      unit: item.unit,
    };
  });
  const $table = xTable.value;
  if ($table) {
    const { row: newRow } = await $table.insertAt(insertData, -1);
    const { tableData } = $table.getTableData();
  }
};
</script>

<style></style>
